<script setup lang="ts">
import { useUserStore } from "@/store/modules/user.store";
import { syncWxUserInfo } from "@/api/user";
import { updateUserInfo } from "@/api/user";

const userStore = useUserStore();

const formRef = ref<any>();

const form = ref({
  user_avatar: "",
  wechat_nickname: ""
});

const rules = ref({
  wechat_nickname: [{ required: true, message: "请输入微信昵称", trigger: "blur" }],
  user_avatar: [{ required: true, message: "请选择用户头像", trigger: "change" }]
});

watch(
  () => form.value.wechat_nickname,
  (newVal) => {
    if (newVal) {
      formRef.value?.validateField("wechat_nickname");
    }
  }
);

watch(
  () => form.value.user_avatar,
  (newVal) => {
    if (newVal) {
      formRef.value?.validateField("user_avatar");
    }
  }
);

const onChooseAvatar = (e: any) => {
  if (e.detail?.avatarUrl) {
    form.value.user_avatar = e.detail.avatarUrl;
  }
};

const wxLogin = () => {
  return new Promise<string>((resolve) => {
    uni.login({
      provider: "weixin",
      success: (res) => {
        if (res.errMsg === "login:ok") {
          resolve(res.code);
        } else {
          resolve("");
        }
      },
      fail: () => {
        resolve("");
      }
    });
  });
};

const getUserProfile = async (e: any) => {
  console.log(JSON.stringify(e));
  if (e.detail?.errMsg === "getUserInfo:ok" && e.detail?.encryptedData) {
    const login_code = await wxLogin();
    if (!login_code) {
      await uni.showToast({
        title: "授权失败",
        icon: "none"
      });
      return uni.navigateBack({
        delta: 2
      });
    }

    try {
      const res = await syncWxUserInfo(e.detail?.encryptedData, e.detail?.iv, login_code);
      console.log(res);
    } catch (error) {}
  }
};

const validate = () => {
  return new Promise((resolve) => {
    formRef.value
      ?.validate()
      .then(() => {
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};

const submit = async () => {
  if (!formRef.value) return;
  if (!userStore.user.isLogin) return;
  const isValid = await validate();
  if (!isValid) return;

  const isAvatarChanged = form.value.user_avatar !== userStore.user.userInfo.avatar;
  const isNicknameChanged = form.value.wechat_nickname !== userStore.user.userInfo.nickname;

  if (!isAvatarChanged && !isNicknameChanged) {
    await uni.showToast({
      title: "更新成功",
      icon: "success"
    });
    return uni.navigateBack({
      delta: 2
    });
  }

  try {
    const res = await updateUserInfo({
      user_avatar: isAvatarChanged ? form.value.user_avatar : undefined,
      user_nickname: form.value.wechat_nickname
    });

    if (res.success) {
      userStore.user = {
        isLogin: true,
        ...res.data
      };
      await await uni.showToast({
        title: "更新成功",
        icon: "success"
      });
      uni.navigateBack({
        delta: 2
      });
    }
  } catch (error) {
    console.log(error);
  }
};

onLoad(() => {
  if (userStore.user.isLogin) {
    form.value.user_avatar = userStore.user.userInfo.avatar;
    form.value.wechat_nickname = userStore.user.userInfo.nickname;
  }
});
</script>
<template>
  <view class="content">
    <view class="app-logo">
      <u-image
        src="https://bbl-1329058988.cos.ap-beijing.myqcloud.com/stick/assets/app_logo.jpg"
        width="200rpx"
        height="200rpx"
      ></u-image>
    </view>
    <view class="app-title">球杆定制</view>
    <view class="agreement-box"> 请完成信息授权后继续使用 </view>
    <view class="form-box">
      <up-form :model="form" :rules="rules" ref="formRef" label-width="100">
        <up-form-item label="用户头像" prop="user_avatar" :borderBottom="true">
          <view class="avamain">
            <button class="avabtn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
              <image
                mode="aspectFill"
                class="uava"
                v-if="form.user_avatar"
                :src="form.user_avatar"
              ></image>
              <view v-else class="uicon">
                <u-icon name="plus" color="#5ac725" size="30"></u-icon>
              </view>
            </button>
          </view>
        </up-form-item>
        <up-form-item label="用户姓名" prop="wechat_nickname" :borderBottom="true">
          <up-input
            type="nickname"
            v-model="form.wechat_nickname"
            placeholder="请输入姓名"
          ></up-input>
        </up-form-item>
        <up-form-item>
          <view class="submit-btn">
            <up-button type="success" size="large" @click="submit">确定</up-button>
          </view>
        </up-form-item>
      </up-form>
    </view>
  </view>
</template>

<style scoped lang="scss">
.content {
  padding: 0;
  .app-logo {
    display: flex;
    justify-content: center;
    padding-top: 8vh;
  }
  .app-title {
    font-size: 45rpx;
    text-align: center;
  }
  .agreement-box {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    margin: 60rpx 0;

    .checkbox-container {
      display: flex;
      align-items: center;
    }

    .checkbox {
      width: 30rpx;
      height: 30rpx;
      box-sizing: border-box;
      border-radius: 3px;
      border: 2rpx solid #8f8f94;
      margin-right: 10rpx;
      transition: all 0.3s ease-in-out;
      display: flex;
      justify-content: center;
      align-items: center;
      &.checked {
        border-color: rgb(60, 197, 31);
      }
    }

    .agreement-text {
      color: rgb(60, 197, 31);
    }

    .mintext {
      font-size: 24rpx;
    }
  }

  .login-btn {
    padding: 0 50rpx;
  }

  .form-box {
    padding: 0 20rpx;

    .avamain {
      width: 100%;
      text-align: left;
      .avabtn {
        width: 170rpx;
        height: 170rpx;
        padding: 5rpx;
        margin: 0 0 10px;
        border: 1px dashed #dadbde;
        .uava {
          width: 100%;
          height: 100%;
        }
        .uicon {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    .submit-btn {
      padding-top: 20rpx;
      width: 100%;
    }
  }
}
</style>
